<template>
  <view class="page">
    <!-- 背景图片 -->
    <image
        src="/static/bj-002.jpg"
        mode="aspectFill"
        class="bg-image">
    </image>

    <scroll-view class="scroll-container" scroll-y>
      <view class="white-box">
        <view class="title-container">
          <view class="back-container" @click="goBack">
            <image class="back-image" src="/static/images/fanhui.png"></image>
          </view>
          <text class="title">作品修改</text>
        </view>

        <view class="form-container">
          <!-- 作品名称 -->
          <view class="single-line-row">
            <text class="field-name">作品名称</text>
            <input
                class="form-input golden-border"
                placeholder="名称10字以内"
                v-model="formData.workName"
                maxlength="10"
                :placeholder-style="placeholderStyle"
            />
          </view>

          <!-- 作品简介 -->
          <view class="single-line-row">
            <text class="field-name">作品简介</text>
            <textarea
                class="form-textarea golden-border"
                placeholder="简介100字以内"
                v-model="formData.remark"
                maxlength="100"
                :placeholder-style="placeholderStyle"
            />
          </view>

          <!-- 作品上传 -->
<!--          <view class="single-line-row">-->
<!--            <text class="field-name">作品上传</text>-->
<!--            <view class="upload-wrapper">-->
<!--              <uni-file-picker-->
<!--                  v-model="fileList"-->
<!--                  file-mediatype="all"-->
<!--                  mode="grid"-->
<!--                  :limit="3"-->
<!--                  :image-styles="imageStyles"-->
<!--                  @delete="handleDelete"-->
<!--                  @select="handleSelect"-->
<!--              >-->
<!--                <view class="upload-area">-->
<!--                  <uni-icons type="plusempty" size="30" color="#3667AA"></uni-icons>-->
<!--                  <text class="upload-tip">点击上传</text>-->
<!--                </view>-->
<!--              </uni-file-picker>-->
<!--            </view>-->
<!--          </view>-->

          <!-- 作品上传 -->
          <view class="single-line-row" v-if="this.formData.workType=='数字创作(动态)'">
            <text class="field-name">作品上传</text>
            <view class="upload-wrapper">
              <uni-file-picker
                  v-model="fileList"
                  file-mediatype="video"
                  mode="grid"
                  :limit="1"
                  :image-styles="imageStyles"
                  @delete="handleDelete"
                  @select="handleSelect"
              >
                <view class="upload-area">
                  <uni-icons type="plusempty" size="30" color="#3667AA"></uni-icons>
                  <text class="upload-tip">点击上传</text>
                </view>
              </uni-file-picker>
              <!-- 新增进度条 -->
              <view v-if="uploadProgress > 0 && uploadProgress < 100" class="progress-bar">
                <text class="progress-text">{{ uploadProgress }}%</text>
                <view class="progress-inner" :style="{ width: uploadProgress + '%' }"></view>
              </view>
            </view>
          </view>
          <view class="single-line-row" v-if="this.formData.workType=='数字创作(静态)'">
            <text class="field-name">作品上传</text>
            <view class="upload-wrapper">
              <uni-file-picker
                  v-model="fileList"
                  file-mediatype="image"
                  mode="grid"
                  :limit="5"
                  :image-styles="imageStyles"
                  @delete="handleDelete"
                  @select="handleSelect"
              >
                <view class="upload-area">
                  <uni-icons type="plusempty" size="30" color="#3667AA"></uni-icons>
                  <text class="upload-tip">点击上传</text>
                </view>
              </uni-file-picker>
            </view>
          </view>
          <view class="single-line-row" v-if="this.formData.workType!='数字创作(动态)' && this.formData.workType!='数字创作(静态)'">
            <text class="field-name">作品上传</text>
            <view class="upload-wrapper">
              <uni-file-picker
                  v-model="fileList"
                  file-mediatype="image"
                  mode="grid"
                  :limit="3"
                  :image-styles="imageStyles"
                  @delete="handleDelete"
                  @select="handleSelect"
              >
                <view class="upload-area">
                  <uni-icons type="plusempty" size="30" color="#3667AA"></uni-icons>
                  <text class="upload-tip">点击上传</text>
                </view>
              </uni-file-picker>
            </view>
          </view>

          <!-- 视频播放器 -->
          <view v-for="(video, index) in videoUrl" :key="'video-' + index" >
            <view class="video-player">
              <video
                  :src="video"
                  controls
                  style="width: 100%; height: 200px;"
              ></video>
            </view>
          </view>

          <!-- 上传提示（单感叹号+间距调整） -->
          <view class="notice-container" v-if="this.formData.workType=='数字创作(动态)'">
            <view class="notice-icon">!</view>
            <view class="notice-content">
              <text>投稿作品需要为 MP4格式,</text>
              <text>解析度不低于1080p，</text>
              <text> 时长2-10分钟。</text>
            </view>
          </view>
          <view class="notice-container" v-if="this.formData.workType=='数字创作(静态)'">
            <view class="notice-icon">!</view>
            <view class="notice-content">
              <text>投稿作品需要为tiff或jpg格式，</text>
              <text>解析度应在300中dpi,</text>
              <text>文件大小：80M以内，</text>
              <text>每组系列作品不超过5张。</text>
            </view>
          </view>
          <view class="notice-container" v-if="this.formData.workType!='数字创作(动态)' && this.formData.workType!='数字创作(静态)'">
            <view class="notice-icon">!</view>
            <view class="notice-content">
              <text> 投稿作品需要为jpg格式</text>
              <text> 解析度应在300dpi,</text>
              <text> 文件大小：10M以内，</text>
              <text> 每人最多可上传3件作品。</text>
            </view>
          </view>


        </view>
      </view>
    </scroll-view>
    <view>
      <text class="submit-btn" @click="handleSubmit">提交</text>
      <image class="cloud-image"
             src="/static/images/yunduo.png"  ></image>
    </view>
  </view>
</template>

<script>
import {getInfo, updateRegistration} from "@/api/activity/activity"
import config from "@/config";

export default {
  data() {
    return {
      placeholderStyle: "color:#999; text-align:left;",
      formData: {
        workName: '',
        thumbnail: '',
        remark: '',
        thumbnails: []
      },
      uploadProgress: 0, // 新增上传进度字段
      fileList: [],
      isSubmitting: false,
      videoUrl: [], // 新增视频URL
      picUrl: [], // 图片URL数组
      imageStyles: {
        width: 80,
        height: 80,
        border: {
          color: '#3667aa',
          width: '1px',
          style: 'solid'
        }
      }
    }
  },
  // 在成功页获取数据
  onLoad(options) {
    if (options.id) {
      const id = decodeURIComponent(options.id);
      getInfo(id).then(res => {
        this.formData = {...this.formData, ...res.data};
        // 新增空数组处理和字段完整性检查
        const baseUrl = config.baseUrl;
        if (this.formData.thumbnail !='') {
          this.formData.thumbnails=this.formData.thumbnail.split(',')
          this.fileList = this.formData.thumbnail.split(',').map(url => ({
            url: baseUrl+url,
            path: url, // 保持与上传时的path一致
            name: url.split('/').pop() || 'unknown.jpg', // 防止路径异常
            extname: url.split('.').pop() || 'jpg', // 根据实际文件名获取扩展名
            uid: Date.now() + Math.random() // 新增唯一标识符
          }));
          this.formData.thumbnails.forEach(url => {
            const fileType = this.getFileTypeFromPath(url); // 增加对文件类型的判断
            if (fileType && fileType.startsWith('video/')) {
              this.videoUrl.push(baseUrl+url);
            }
            if (fileType && fileType.startsWith('image/')) {
              this.picUrl.push(baseUrl+url);
            }
          });
        } else {
          this.fileList = [];
        }
        console.log('ID:', this.formData);
        console.log('ID:', this.formData.workType);
      })
    }
  },
  methods: {
    handleSelect(e) {
      const baseUrl = config.baseUrl;
      const files = e.tempFiles;
      const file = files[0];
      const fileType = file.type || this.getFileTypeFromPath(file.name); // 增加对文件类型的判断

      // 使用 Promise 包装 uni.uploadFile
      this.uploadTask = new Promise((resolve, reject) => {
        const uploadTask = uni.uploadFile({
          url: baseUrl + '/common/upload',
          filePath: file.path,
          name: 'file',
          success: (res) => resolve(res),
          fail: (err) => reject(err)
        });
        // 绑定 onProgressUpdate 事件
        uploadTask.onProgressUpdate((res) => {
          this.uploadProgress = res.progress || 0; // 更新上传进度
        });
      });

      // 处理上传结果
      this.uploadTask.then(res => {
        try {
          const response = JSON.parse(res.data);
          if (Array.isArray(this.formData.thumbnails)) {
            this.formData.thumbnails.push(response.fileName);
          } else {
            this.formData.thumbnails = [response.fileName];
          }
          this.fileList.push({
            url: baseUrl + response.fileName,
            path: response.fileName,
            name: response.fileName.split('/').pop() || 'unknown.jpg',
            extname: response.fileName.split('.').pop() || 'jpg',
            uid: Date.now() + Math.random()
          });
          if (fileType && fileType.startsWith('video/')) {
            this.videoUrl.push(baseUrl + response.fileName);
          }
          if (fileType && fileType.startsWith('image/')) {
            this.picUrl.push(baseUrl + response.fileName);
          }
        } catch (error) {
          console.error('解析上传响应失败', error);
        }
      }).catch(err => {
        console.error('上传失败:', err);
        uni.showToast({ title: '上传失败', icon: 'none' });
      });
      return true
    },

    goBack() {
      // setTimeout(() => {
      //   uni.navigateBack({ delta: 1 });
      // }, 100);
      uni.navigateTo({
        url: '/pages/saishi/edit'
      })
    },
    // 新增方法从文件路径中获取文件类型
    getFileTypeFromPath(path) {
      const ext = path.split('.').pop().toLowerCase();
      const imageTypes = ['jpg', 'jpeg', 'png', 'gif', 'bmp'];
      const videoTypes = ['mp4', 'mov', 'avi', 'wmv', 'flv'];
      if (imageTypes.includes(ext)) {
        return 'image/' + ext;
      } else if (videoTypes.includes(ext)) {
        return 'video/' + ext;
      }
      return null;
    },

    // 添加删除作品方法
    handleDelete(e) {
      let url = e.tempFile.url;
      this.formData.thumbnails = this.formData.thumbnails.filter(item => !url.includes(item));
      this.fileList = this.fileList.filter(item => url!==item.url);
      this.videoUrl = this.videoUrl.filter(item => url!==item);
      this.picUrl = this.picUrl.filter(item => url!==item);
    },

    async handleSubmit() {
      if (this.isSubmitting) return
      this.isSubmitting = true

      try {
        let param = {
          ...this.formData,
          thumbnail: this.formData.thumbnails.join(",")
        }
        updateRegistration(param).then(response => {
          uni.showToast({
            title: '作品提交成功',
            icon: 'success'
          });
          setTimeout(() => {
            uni.navigateBack({ delta: 1 });
          }, 1000);
        })
      } catch (error) {
        uni.showToast({ title: '提交失败，请重试', icon: 'none' })
      } finally {
        this.isSubmitting = false
      }
    }
  }
}
</script>

<style>
@font-face {
  font-family: 'minikt';
  src: url('@/static/font/minikt.TTF') format('truetype');
}
.page {
  position: relative;
  width: 100%;
  height: 100vh;
  overflow: hidden;
}

.bg-image {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: -1; /* 让背景在底层 */
}

.scroll-container {
  position: relative;
  z-index: 1;
  height: 90%;
  width: 100%;
}

.white-box {
  width: 90vw;
  max-width: 800px;
  background-color: #ffffff;
  border-radius: 16px;
  padding: 30px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  margin: 30px auto;
}

.title {
  color: #004AAC;
  font-size: 50rpx;
  font-weight: bold;
  font-family: 'minikt', sans-serif;;
  text-align: center;
  display: block;
  margin-bottom: 30px;
}

/* 表单行样式 */
.single-line-row {
  display: flex;
  align-items: flex-start;
  margin-bottom: 20px; /* 减小行间距 */
  flex-wrap: wrap;
}

.field-name {
  font-size: 30rpx;
  color: #333;
  width: 120rpx;
  text-align: justify;
  text-align-last: justify;
  margin-right: 10px;
  flex-shrink: 0;
}

/* 输入框样式 */
.form-input {
  flex: 1;
  border: 1px solid #3667AA;
  border-radius: 6px;
  padding: 10px 12px;
  font-size: 14px;
  background-color: white;
  min-width: 0;
  height: 40px;
}

/* 文本域样式 */
.form-textarea {
  flex: 1;
  border: 1px solid #3667AA;
  border-radius: 6px;
  padding: 12px;
  font-size: 14px;
  background-color: white;
  min-width: 0;
  height: 100px;
  line-height: 1.5;
}

/* 上传区域 */
.upload-wrapper {
  flex: 1;
}

.upload-area {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 80px;
  border: 1px solid #3667AA;
  border-radius: 6px;
  background-color: #FFFFFF;
}

.upload-tip {
  font-size: 12px;
  color: #3667AA;
  margin-top: 5px;
}

/* 上传提示样式（新版） */
.notice-container {
  display: flex;
  margin-top: 15px; /* 增加与上传区域的间距 */
  margin-left: 80px; /* 与字段名对齐 */
  margin-bottom: 20px;
}

.notice-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 20px; /* 调大尺寸 */
  height: 20px;
  background-color: #ff0000;
  color: white;
  border-radius: 50%;
  font-size: 14px; /* 调大字体 */
  font-weight: bold;
  margin-right: 8px;
  flex-shrink: 0;
}

.notice-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  font-size: 13px;
  color: #666;
  line-height: 1.6;
}



.submit-btn:active {
  opacity: 0.8;
}

/* 视频播放器样式 */
.video-player {
  margin-left: 160rpx; /* 向右偏移200rpx */
  margin-top: 20px;
  margin-bottom: 20px;
}
.submit-btn {
  position: absolute;
  bottom: 20px;
  left: 50%;
  transform: translateX(-50%);
  z-index: 3; /* 确保按钮在上层 */
  color: #004AAC;
  font-size: 50rpx;
  font-weight: bold;
  font-family: 'minikt', sans-serif;
  text-align: center;
  display: block;
  padding: 10px 20px;
  border-radius: 10px;
}

.cloud-image {
  position: absolute;
  bottom: -45rpx;
  left: 50%;
  transform: translateX(-48%);
  width: 380rpx; /* 调整宽度为600rpx */
  height: 250rpx;
  z-index: 2; /* 确保图片在下层 */
  opacity: 1; /* 添加透明度，使白云图案与背景图融合 */
}

.title-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 30px;
}

.back-container {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}
.back-image {
  width: 500rpx;
  height: 70rpx;
  margin-left: -280rpx; /* 调整图片和文字之间的间距 */
}
/* 新增进度条样式 */
.progress-bar {
  width: 100%;
  height: 10px;
  background-color: #e14b4b;
  border-radius: 5px;
  margin-top: 10px;
  position: relative;
}

.progress-inner {
  height: 100%;
  background-color: #3667AA;
  border-radius: 5px;
  transition: width 0.3s ease-in-out;
}

.progress-text {
  position: absolute;
  top: -20px;
  left: 50%;
  transform: translateX(-50%);
  font-size: 12px;
  color: #3667AA;
}
</style>
